package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.qo.PageQuery;
import com.itheima.vo.PageResult;
import com.itheima.vo.Result;
import com.itheima.vo.UserLoginVo;
import com.itheima.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    //加final
    private final UserService userService;

    /***
     * 登录
     * 1)接收参数
     * 2)查询数据库对应账号密码的用户
     * 3)查得到，登录成功，生成令牌，并颁发令牌
     * 4)查不到，登录失败，提示错误信息
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        UserLoginVo vo = userService.login(user);

        Result result = new Result();
        if(vo==null){
            result.setMsg("账号或密码错误");
            result.setCode(404);
            return result;
        }
        //响应结果封装

        result.setData(vo);
        result.setCode(200);
        return result;
    }



    /***
     * 分页查询  PageQuery
     */
    @PostMapping("/page")
    public PageResult page(@RequestBody PageQuery<User> pageQuery){
        PageResult pageResult = userService.page(pageQuery);
        return pageResult;
    }

    /***
     * 添加用户
     */
    @PostMapping
    public Result add(@RequestBody User user){
        Result result = new Result();
        userService.add(user);
        result.setCode(200);
        result.setMsg("添加成功");
        return result;
    }

    /***
     * 根据id回显用户
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Result result = new Result();
        User user = userService.getById(id);  // 获取查询结果
        result.setData(user);                  // 将查询结果设置到返回对象中
        result.setCode(200);
        result.setMsg("操作成功");
        return result;
    }

    /***
     * 修改用户
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        Result result = new Result();
        userService.update(user);
        result.setCode(200);
        result.setMsg("修改成功");
        return result;
    }

    /***
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        Result result = new Result();
        userService.deleteById(id);
        result.setCode(200);
        result.setMsg("删除成功");
        return result;
    }
}
